package com.lw.sms.controller;

import com.lw.commonutil.result.Result;
import com.lw.commonutil.result.ResultCodeEnum;
import com.lw.sms.service.SmsService;
import com.lw.sms.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/sms")
public class SmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    RedisTemplate redisTemplate;
    //发送手机短信
    @GetMapping("/send/{phone}")
    public Result send(@PathVariable String phone){
        //查询该手机号是否存在验证码
        String code=null;
        code = (String) redisTemplate.opsForValue().get(phone);
        if (code!=null){
            return Result.build( null, ResultCodeEnum.SEND_RIBBON );
        }
        //生成验证码
        code = RandomUtil.getFourBitRandom();
        redisTemplate.opsForValue().set( phone,code,5, TimeUnit.MINUTES );
        //调用service发送验证码
        boolean flag = smsService.send(phone,code);
        if (flag){
            return Result.ok();
        }else {
            return Result.fail();
        }
    }
}
